<template>
  <div class="app-container page-container">
    <div class="search-area">
      <el-date-picker
        v-model="timeRange"
        size="small"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        clearable
        @change="fetchData(1)"
      />
      <el-select v-model="pid" placeholder="请选择大机" size="small" clearable style="margin-left: 12px" @change="fetchData(1)">
        <el-option
          v-for="item in machineOptions"
          :key="item.id"
          :label="item.deviceName"
          :value="item.id"
        />
      </el-select>
      <el-select v-model="statisticalType" style="margin-left: 12px" placeholder="请选择分类" size="small" clearable @change="fetchData(1)">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" size="small" style="margin-left: 12px" @click="handleDownload">导出</el-button>
    </div>
    <div class="table-container">
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        border
        highlight-current-row
        height="100%"
        style="width: 100%"
        :header-cell-style="{
          background:'#6c89e7',
          color:'#000000'
        }"
        :row-style="handleRowStyle"
        @selection-change="handleSelectionChange"
      >
        <!--        <el-table-column-->
        <!--          type="selection"-->
        <!--          width="55"-->
        <!--        />-->
        <el-table-column label="起重机号" prop="craneName" />
        <el-table-column label="名称" prop="deviceName" />
        <el-table-column label="更换时间" prop="deviceReplacementTime" />
        <el-table-column label="负责人" prop="owner" />
        <el-table-column label="统计类型" prop="statisticalType" />
        <el-table-column label="统计值" prop="statisticalValue" />
        <el-table-column label="备注" prop="remark" />
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        :current-page="pageNumber"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { queryDeviceMaintainRecordsList, queryDeviceList, downloadDeviceMaintainRecords } from '../../api/device'
import * as dayjs from 'dayjs'
import { queryDictList } from '@/api/dict'

export default {
  name: 'MaintainRecords',
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      machineOptions: [],
      options: [],
      statisticalType: undefined,
      pid: undefined,
      list: null,
      listLoading: true,
      multipleSelection: [],
      pageSize: 10,
      pageNumber: 1,
      total: 0,
      timeRange: []
    }
  },
  mounted() {
    this.fetchData()
    this.getMachineList()
    this.getDictList(0, 'options')
  },
  methods: {
    getMachineList() {
      queryDeviceList().then(({ data, success }) => {
        if (success) {
          this.machineOptions = data || []
        }
      })
    },
    handleRowStyle({ _, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return {
          'background-color': '#cfd6e6'
        }
      }
      return {
        'background-color': '#e8ecf5'
      }
    },
    fetchData(page) {
      this.listLoading = true
      queryDeviceMaintainRecordsList({
        pageNumber: page || this.pageNumber,
        pageSize: this.pageSize,
        statisticalType: this.statisticalType,
        pid: this.pid,
        startTime: this.timeRange?.length ? this.timeRange[0] : undefined,
        endTime: this.timeRange?.length ? this.timeRange[1] : undefined
      }).then(({ data, success }) => {
        if (success) {
          this.list = data?.data || []
          this.total = data?.total || 0
          if (page) this.pageNumber = page
        }
      }).finally(() => { this.listLoading = false })
    },
    handleDelete() {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData(1)
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.fetchData()
    },
    handleDownload() {
      downloadDeviceMaintainRecords({
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        statisticalType: this.statisticalType,
        pid: this.pid,
        startTime: this.timeRange?.length ? this.timeRange[0] : undefined,
        endTime: this.timeRange?.length ? this.timeRange[1] : undefined
      }).then(resp => {
        if (resp) {
          const a = document.createElement('a')
          const url = window.URL.createObjectURL(new Blob([resp]))
          // 创建url对象
          a.href = url
          a.download = `维护记录-${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
          a.click()
          // 释放url对象
          window.URL.revokeObjectURL(url)
        }
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getDictList(dictType, field) {
      queryDictList({ dictType }).then(({ data, success }) => {
        if (success) {
          this[field] = data || []
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-area {
  margin-bottom: 16px;
  text-align: right;
}
.table-container {
  height: calc(100vh - 215px);
}
.pagination-container {
  margin-top: 10px;
}
</style>
